import { createRouter, createWebHistory } from 'vue-router'
import Api from '@/api/api'
import {mainStore} from '@/store/index.js'

const routes = [
    {
        path: '/',
        redirect: '/login',
    },
    {
        path: '/home',
        name: 'Home',
        component: () => import('../views/home/index.vue'),
        children:[]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login/index.vue')
    }
]

// 资源转化路由
function addDynamicRoute(data) {
    const homeRoute = routes.filter(v => p.path === '/home')[0]
    homeRoute.children = []
    data.forEach(item => {
        homeRoute.children.push({
            path: item.path,
            name: item.title,
            component: () => import(`../views/home/content/${item.component}/index.vue`),
        })
    });
    return homeRoute;
}

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由拦截
router.beforeEach(async (to, from, next) => {
    if (to.path === '/login') {
        next()
    }else {
        if (mainStore()?.nav?.length ==0 ) {
            // 发送请求获取转化路由信息
            // const {data: {res}} = await Api.getUserResources()
            const res = [
                {name:'index', title: '首页1', icon: 'el-icon-s-home', path: '/home/index',component:'index'},
                {name:'index2',title: '首页2', icon: 'el-icon-s-home', path: '/home/index',component:'index'},
            ]
            // 缓存
            mainStore.setNav(res)
            const dynamicRoute = addDynamicRoute(res)
            // 动态配置路由
            router.addRoute(dynamicRoute)
        }

        next()
    }
})

export default router